package api;

import com.alibaba.fastjson.JSON;
import common.pojo.CommonResult;
import common.utils.JsonUtils;
import common.utils.ObjectId;
import httpclient.HttpClientUtils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.NumberUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import service.WxUserInfoService;
import service.cfg.GoodsCfg;
import service.cfg.ImageCfg;
import service.cfg.ResourceApiFrameworkCfg;
import service.cfg.WxCfg;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import javax.swing.*;
import java.awt.*;
import java.awt.font.TextAttribute;
import java.awt.geom.AffineTransform;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by asus on 2018/10/18.
 */
@Service
public class QrcodeApi {

    private static final Logger LOG = LoggerFactory.getLogger(QrcodeApi.class);

    @Autowired
    WxCfg wxCfg;

    @Autowired
    ImageCfg imageCfg;

    @Autowired
    WxUserInfoService infoService;
    @Autowired
    protected ResourceApiFrameworkCfg cfg;

    @Autowired
    GoodsCfg goodsCfg;

    private static final String grantType = "client_credential";

    private static final String codeUrl = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=%s";

    private static final String tokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s";

    /**
     * 获取token
     *
     * @param
     * @return
     */
    public String getAccessToken() {
        String url = String.format(tokenUrl, wxCfg.getApp_id(), wxCfg.getApp_secret());
        String result = HttpClientUtils.getBodyStr(url);
        LOG.warn("---getAccessToken--" + result);
        Map maps = (Map) JSON.parse(result);
        return maps.get("access_token").toString();
    }

    /**
     * 生成个人二维码返回图片保存路径
     *
     * @param map
     * @param token
     * @param openId
     * @return
     */
    public CommonResult returnCodeMine(Map map, String token, String openId) {
        String url = String.format(codeUrl, token);
        RestTemplate rest = new RestTemplate();
        OutputStream outputStream = null;
        String fileName = "mine" + openId + ".png";
        String imgPath = this.cfg.getMaterialFileRootPath() + "/" + fileName;
        String params = "";
        if (map.containsKey("shopId")) {
            params = "3#" + map.get("parentId").toString() + "#" + map.get("shopId").toString();
        } else {
            params = "3#" + map.get("parentId").toString();
        }
        try {
            Map<String, Object> param = new HashMap<>();
            param.put("scene", params);
            param.put("page", "pages/businessCard/businessCard"); //小程序跳转页面上线后启用
//             param.put("width", ""); //二维码宽度
//             param.put("auto_color", "");//true // false  自动配置线条颜色，如果颜色依然是黑色，则说明不建议配置主色调，默认 false
//             param.put("line_color", "");//line_color auto_color 为 false 时生效，使用 rgb 设置颜色 例如 {"r":"xxx","g":"xxx","b":"xxx"} 十进制表示，默认全 0
//             param.put("is_hyaline", "");//是否需要透明底色，为 true 时，生成透明底色的小程序码，默认 false

            MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
            headers.add("content-type", "application/json");
            HttpEntity requestEntity = new HttpEntity(param, headers);
            ResponseEntity<byte[]> entity = rest.exchange(url, HttpMethod.POST, requestEntity, byte[].class, new Object[0]);
            int length = entity.getBody().length;  //68
            if (length < 100) {
                LOG.warn("----小程序二维码生成结果----" + new String(entity.getBody()));
                return CommonResult.returnFailsWrapper("小程序二维码生成异常" + new String(entity.getBody()));
            }
            byte[] result = entity.getBody();
            File file = new File(imgPath);
            if (!file.exists()) {
                file.createNewFile();
            }
            outputStream = new FileOutputStream(file);
            outputStream.write(result);
            outputStream.flush();
            //加上头像
            String headUrl = map.get("headUrl").toString();

            if (!StringUtils.isEmpty(headUrl)) {
                this.addHeaderQrcode(imgPath, headUrl);
            }
        } catch (Exception e) {
            LOG.warn("----小程序二维码生成异常----" + e.toString());
            System.out.println("调用小程序生成微信永久小程序码URL接口异常");
            return CommonResult.returnFailsWrapper("小程序二维码生成异常" + e.toString());
        } finally {

            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            String path = String.format("%s/image/%s", this.cfg.getMaterialHttpRootUrl(), fileName);
            infoService.updateMineQrcode(path, openId);
            return CommonResult.returnDataWrapper(path);
        }
    }

    /**
     * 店主
     *
     * @param map
     * @param token
     * @param openId
     * @return
     */
    public CommonResult returnCode(Map map, String token, String openId) {
        String url = String.format(codeUrl, token);
        RestTemplate rest = new RestTemplate();
        OutputStream outputStream = null;
        String fileName = openId + ".png";
        String imgPath = this.cfg.getMaterialFileRootPath() + "/" + fileName;
        String params = "1#" + map.get("parentId").toString() + "#" + map.get("shopId").toString();
        try {
            Map<String, Object> param = new HashMap<>();
            param.put("scene", params);
            param.put("page", "pages/businessCard/businessCard");  //小程序跳转页面上线后启用
//             param.put("width", ""); //二维码宽度
//             param.put("auto_color", "");//true // false  自动配置线条颜色，如果颜色依然是黑色，则说明不建议配置主色调，默认 false
//             param.put("line_color", "");//line_color auto_color 为 false 时生效，使用 rgb 设置颜色 例如 {"r":"xxx","g":"xxx","b":"xxx"} 十进制表示，默认全 0
//             param.put("is_hyaline", "");//是否需要透明底色，为 true 时，生成透明底色的小程序码，默认 false

            MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
            headers.add("content-type", "application/json");
            HttpEntity requestEntity = new HttpEntity(param, headers);
            ResponseEntity<byte[]> entity = rest.exchange(url, HttpMethod.POST, requestEntity, byte[].class, new Object[0]);
            int length = entity.getBody().length;  //68
            if (length < 100) {
                LOG.warn("----小程序二维码生成结果----" + new String(entity.getBody()));
                return CommonResult.returnFailsWrapper("小程序二维码生成异常" + new String(entity.getBody()));
            }
            byte[] result = entity.getBody();
            File file = new File(imgPath);
            if (!file.exists()) {
                file.createNewFile();
            }
            outputStream = new FileOutputStream(file);
            outputStream.write(result);
            outputStream.flush();
            //加上头像

            //    this.addHeaderQrcode(imgPath,"https://ai.yncljk.com/resapi/material/image/image/default/201812/5c0a629fe6ad411a5e92f8e9@2191x2231.png/210,210");
        } catch (Exception e) {
            LOG.warn("----小程序二维码生成异常----" + e.toString());
            System.out.println("调用小程序生成微信永久小程序码URL接口异常");
            return CommonResult.returnFailsWrapper("小程序二维码生成异常" + e.toString());
        } finally {

            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            String path = String.format("%s/image/%s", this.cfg.getMaterialHttpRootUrl(), fileName);
            return CommonResult.returnDataWrapper(path);
        }
    }

    /**
     * 代理商qrCode
     *
     * @param token
     * @param agentId
     * @return
     */
    public CommonResult returnQrCode(String token, Long agentId) {
        String url = String.format(codeUrl, token);
        RestTemplate rest = new RestTemplate();
        OutputStream outputStream = null;
        String fileName = agentId + ".png";
        String imgPath = this.cfg.getMaterialFileRootPath() + "/" + fileName;
        try {
            String params = "2#" + agentId;
            Map<String, Object> param = new HashMap<>();
            param.put("scene", params);
            param.put("page", "pages/businessCard/businessCard"); //小程序跳转页面上线后启用
//             param.put("width", ""); //二维码宽度
//             param.put("auto_color", "");//true // false  自动配置线条颜色，如果颜色依然是黑色，则说明不建议配置主色调，默认 false
//             param.put("line_color", "");//line_color auto_color 为 false 时生效，使用 rgb 设置颜色 例如 {"r":"xxx","g":"xxx","b":"xxx"} 十进制表示，默认全 0
//             param.put("is_hyaline", "");//是否需要透明底色，为 true 时，生成透明底色的小程序码，默认 false

            MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
            headers.add("content-type", "application/json");
            HttpEntity requestEntity = new HttpEntity(param, headers);
            ResponseEntity<byte[]> entity = rest.exchange(url, HttpMethod.POST, requestEntity, byte[].class, new Object[0]);
            int length = entity.getBody().length;  //68
            if (length < 100) {
                LOG.warn("----小程序二维码生成结果----" + new String(entity.getBody()));
                return CommonResult.returnFailsWrapper("小程序二维码生成异常" + new String(entity.getBody()));
            }
            byte[] result = entity.getBody();
            File file = new File(imgPath);
            if (!file.exists()) {
                file.createNewFile();
            }
            outputStream = new FileOutputStream(file);
            outputStream.write(result);
            outputStream.flush();
            //加上头像

            this.addHeaderQrcode(imgPath, "https://ai.yncljk.com/resapi/material/image/image/default/201812/5c0a629fe6ad411a5e92f8e9@2191x2231.png/210,210");
        } catch (Exception e) {
            LOG.warn("----小程序二维码生成异常----" + e.toString());
            System.out.println("调用小程序生成微信永久小程序码URL接口异常");
            return CommonResult.returnFailsWrapper("小程序二维码生成异常" + e.toString());
        } finally {

            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            String path = String.format("%s/image/%s", this.cfg.getMaterialHttpRootUrl(), fileName);
            return CommonResult.returnDataWrapper(path);
        }
    }


    public BufferedImage getNetWorkImg(String imgUrl){
        try {
            LOG.warn("284");
            LOG.warn(imgUrl);
            int code = testWsdlConnection(imgUrl);
            if (code == 200) {
                URL url = new URL(imgUrl);
                //打开链接
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                //设置请求方式为"GET"
                conn.setRequestMethod("GET");
                //超时响应时间为5秒
                conn.setConnectTimeout(5 * 1000);
                //通过输入流获取图片数据
                InputStream inStream = conn.getInputStream();
                LOG.warn("295");
                BufferedImage bufferedImage = ImageIO.read(inStream);
                return bufferedImage;
            }
        }catch (Exception e){
            LOG.warn("299");
            LOG.warn(e.toString());
            return null;
        }
        return null;
    }


    public BufferedImage getNetWorkImgIo(String filePath){
        try {
            int code = testWsdlConnection(filePath);
            if (code == 200) {
                URL url = new URL(filePath);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                //设置请求方式为"GET"
                conn.setRequestMethod("GET");
                //超时响应时间为5秒
                conn.setConnectTimeout(5 * 1000);
                //通过输入流获取图片数据
                InputStream inStream = conn.getInputStream();
                BufferedImage bufferedImage = ImageIO.read(inStream);
                return bufferedImage;
            }
        }catch (Exception e){
            LOG.warn("--读取网络图片异常-----");
            return null;
        }
        LOG.warn("--读取网络图片异常-----");
        return null;
    }

    public void addHeaderQrcode(String filePath, String head) {
        try {
            int code = testWsdlConnection(head);
            if (code == 200) {
                URL url = new URL(head);
                //打开链接
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                //设置请求方式为"GET"
                conn.setRequestMethod("GET");
                //超时响应时间为5秒
                conn.setConnectTimeout(5 * 1000);
                //通过输入流获取图片数据
                InputStream inStream = conn.getInputStream();
                BufferedImage bufferedImage = ImageIO.read(inStream);
                if (bufferedImage.getWidth() > bufferedImage.getHeight()) {
                    bufferedImage = bufferedImage.getSubimage(0, 0, bufferedImage.getHeight(), bufferedImage.getHeight());
                } else {
                    bufferedImage = bufferedImage.getSubimage(0, 0, bufferedImage.getWidth(), bufferedImage.getWidth());
                }
                bufferedImage = setRadius(bufferedImage, 200, 0, 3);
                LOG.warn(filePath);
                LOG.warn(filePath);
                try {
                    BufferedImage appletImg = ImageIO.read(new FileInputStream(filePath));

                    Graphics2D g2d = appletImg.createGraphics();
                    // 设置抗锯齿的属性
                    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                    g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

                    g2d.drawImage(bufferedImage.getScaledInstance(200, 200, Image.SCALE_SMOOTH), (appletImg.getWidth() - 200) / 2, (appletImg.getHeight() - 200) / 2, null);

                    // 关闭资源
                    g2d.dispose();
                    ImageIO.write(appletImg, "png", new File(filePath));
                } catch (Exception e) {
                    LOG.warn(e.toString());
                    LOG.warn(filePath);
                }

            }
        } catch (Exception e) {
            LOG.warn("---二维码添加头像异常---");
        }

    }

    /***
     * 圆角图片
     * @param srcImage
     * @param radius
     * @param border
     * @param padding
     * @return
     * @throws IOException
     */
    public static BufferedImage setRadius(BufferedImage srcImage, int radius, int border, int padding) throws IOException {
        int width = srcImage.getWidth();
        int height = srcImage.getHeight();
        int canvasWidth = width + padding * 2;
        int canvasHeight = height + padding * 2;

        BufferedImage image = new BufferedImage(canvasWidth, canvasHeight, BufferedImage.TYPE_INT_ARGB);
        Graphics2D gs = image.createGraphics();
        gs.setComposite(AlphaComposite.Src);
        gs.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        gs.setColor(Color.WHITE);
        gs.fill(new RoundRectangle2D.Float(0, 0, canvasWidth, canvasHeight, radius, radius));
        gs.setComposite(AlphaComposite.SrcAtop);
        gs.drawImage(setClip(srcImage, radius), padding, padding, null);
        if (border != 0) {
            gs.setColor(Color.GRAY);
            gs.setStroke(new BasicStroke(border));
            gs.drawRoundRect(padding, padding, canvasWidth - 2 * padding, canvasHeight - 2 * padding, radius, radius);
        }
        gs.dispose();
        return image;
    }

    public static BufferedImage setClip(BufferedImage srcImage, int radius) {
        int width = srcImage.getWidth();
        int height = srcImage.getHeight();
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        Graphics2D gs = image.createGraphics();

        gs.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        gs.setClip(new RoundRectangle2D.Double(0, 0, width, height, radius, radius));
        gs.drawImage(srcImage, 0, 0, null);
        gs.dispose();
        return image;
    }

    public static int testWsdlConnection(String address) throws Exception {
        int status = 404;
        try {
            URL urlObj = new URL(address);
            HttpURLConnection oc = (HttpURLConnection) urlObj.openConnection();
            oc.setUseCaches(false);
            oc.setConnectTimeout(3000); // 设置超时时间
            status = oc.getResponseCode();// 请求状态
            if (200 == status) {
                // 200是请求地址顺利连通。。
                return status;
            }
        } catch (Exception e) {
            LOG.warn(415+e.toString());
            e.printStackTrace();
            throw e;
        }
        return status;
    }

    /**
     * 生成商品分销二维码返回图片系统路径
     * @param map
     * @param token
     * @param
     * @return
     */
    public CommonResult getGoodsCode(Map map, String token) {
        LOG.warn(JsonUtils.toJson(map)+453);
        String url = String.format(codeUrl, token);
        RestTemplate rest = new RestTemplate();
        OutputStream outputStream = null;
        String fileName = new Date().getTime() + ".png";
        String imgPath = this.cfg.getMaterialFileRootPath() + "/" + fileName;
        String params = "";
        params = "4#" + map.get("goodsId").toString() + "#" + map.get("shareId").toString()+"#"+map.get("shareUpId").toString();
        try {
            Map<String, Object> param = new HashMap<>();
            param.put("scene", params);
           param.put("page", "pages/goodsInfo/goodsInfo"); //小程序跳转页面上线后启用
//             param.put("width", ""); //二维码宽度
//             param.put("auto_color", "");//true // false  自动配置线条颜色，如果颜色依然是黑色，则说明不建议配置主色调，默认 false
//             param.put("line_color", "");//line_color auto_color 为 false 时生效，使用 rgb 设置颜色 例如 {"r":"xxx","g":"xxx","b":"xxx"} 十进制表示，默认全 0
//             param.put("is_hyaline", "");//是否需要透明底色，为 true 时，生成透明底色的小程序码，默认 false

            MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
            headers.add("content-type", "application/json");
            HttpEntity requestEntity = new HttpEntity(param, headers);
            ResponseEntity<byte[]> entity = rest.exchange(url, HttpMethod.POST, requestEntity, byte[].class, new Object[0]);
            int length = entity.getBody().length;  //68
            if (length < 100) {
                LOG.warn("----小程序二维码生成结果----" + new String(entity.getBody()));
                return CommonResult.returnFailsWrapper("小程序二维码生成异常" + new String(entity.getBody()));
            }
            byte[] result = entity.getBody();
            File file = new File(imgPath);
            if (!file.exists()) {
                file.createNewFile();
            }
            outputStream = new FileOutputStream(file);
            outputStream.write(result);
            outputStream.flush();
            //加上头像
            String headUrl = map.get("headUrl").toString();
            if (!StringUtils.isEmpty(headUrl)) {
                this.addHeaderQrcode(imgPath, headUrl);
            }
        } catch (Exception e) {
            LOG.warn("----小程序二维码生成异常----" + e.toString());
            System.out.println("调用小程序生成微信永久小程序码URL接口异常");
            return CommonResult.returnFailsWrapper("小程序二维码生成异常" + e.toString());
        } finally {

            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return CommonResult.returnDataWrapper(imgPath);
        }
    }

    public CommonResult getGoodsPoster(Map map, String token,String wxName) throws IOException {
        LOG.warn(map.get("shareUpId").toString()+":"+510);
        String fileName = new Date().getTime() + ".png";
        String imgPath = this.cfg.getMaterialFileRootPath2() + "/" + fileName;
        Long goodsId= org.apache.commons.lang.math.NumberUtils.toLong(map.get("goodsId").toString());
        Map goodsMap = new HashMap();
        System.out.println(481);
        LOG.warn("---481---");
        if(goodsId>0){
            CommonResult goodsResult=HttpClientUtils.get(goodsCfg.getGoodsInfo(goodsId));
            if(goodsResult.getData()!=null){
                LOG.warn("----商品获取失败----" );
                return CommonResult.returnFailsWrapper("商品获取失败");
            }
            goodsMap.putAll(goodsResult);
            if(goodsMap.size()==0){
                LOG.warn("----商品获取失败----" );
                return CommonResult.returnFailsWrapper("商品获取失败");
            }
        }
        File files = new File(cfg.getGoodsPosterMode());
        BufferedImage appletImg=null;
        if(files.exists()){
            if(files.isFile()){
                LOG.warn("531");
                appletImg = ImageIO.read(files);
                LOG.warn(appletImg.getData().toString());
            }
        }else {
            LOG.warn("mode.png不存在");
            appletImg=this.getNetWorkImgIo("https://ai.yncljk.com/goodsPoster/mode.png");
        }
        if(appletImg==null){
            return CommonResult.returnFailsWrapper("跟文件读取失败");
        }
        LOG.warn(cfg.getGoodsPosterMode());
        Graphics2D g2d = appletImg.createGraphics();
        // 设置抗锯齿的属性
        g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
        System.out.println(546);
        //设置标题
        Font font = new Font("宋体", Font.ITALIC, 50);
        g2d.setFont(font);
        g2d.setColor(Color.black);
        LOG.warn(goodsMap.get("name").toString());
        System.out.println(552);
        g2d.drawString(goodsMap.get("name").toString(), 50, 100);
        System.out.println(554);
        //填写商品图片
        BufferedImage bufferedImage = this.getNetWorkImg(goodsMap.get("mainImg").toString());
        System.out.println(557);
        if(bufferedImage==null){
            return CommonResult.returnFailsWrapper("商品主图获取失败");
        }
        if (bufferedImage.getWidth() > bufferedImage.getHeight()) {
            bufferedImage = bufferedImage.getSubimage(0, 0, bufferedImage.getHeight(), bufferedImage.getHeight());
        } else {
            bufferedImage = bufferedImage.getSubimage(0, 0, bufferedImage.getWidth(), bufferedImage.getWidth());
        }
        g2d.drawImage(bufferedImage.getScaledInstance(655, 655, Image.SCALE_SMOOTH), 47, 150, null);
        //写商品介绍
        String text=goodsMap.get("res").toString();
        System.out.println(525);
        if(text.length()>16){
            Font f = new Font("宋体", Font.BOLD, 25);
            g2d.setFont(f);
            g2d.setColor(Color.black);
            FontMetrics fm =sun.font.FontDesignMetrics.getMetrics(f);
            //16个字体一行
            int width = SwingUtilities.computeStringWidth(fm, text);
            int height = fm.getHeight();
            if(text.length()>=16 && text.length()<=23){
                g2d.drawString(text.substring(0,text.length()), 79,870);
                if(text.length()<=43 && text.length()>23){
                    g2d.drawString(text.substring(23,text.length())+"...", 79,870+height);
                }
            }
            System.out.println(539);
        }else {
            Font f = new Font("宋体", Font.BOLD, 35);
            g2d.setFont(f);
            g2d.setColor(Color.black);
            FontMetrics fm =sun.font.FontDesignMetrics.getMetrics(f);
            int width = SwingUtilities.computeStringWidth(fm, text);
            g2d.drawString(text.substring(0,text.length()), 79,880);
            System.out.println(551);
        }
        //写价格
        Font f1 = new Font("宋体", Font.BOLD, 38);
        g2d.setFont(f1);
        g2d.setColor(Color.red);
        int widthPrice=0;
        if(org.apache.commons.lang.math.NumberUtils.toDouble(goodsMap.get("salesPrice").toString())<100){
            g2d.drawString("¥"+goodsMap.get("salesPrice").toString(), 280,950);
            widthPrice=280;
        }else {
            g2d.drawString("¥"+goodsMap.get("salesPrice").toString(), 280,950);
            widthPrice=280;
        }


        FontMetrics fm =sun.font.FontDesignMetrics.getMetrics(f1);
        int width = SwingUtilities.computeStringWidth(fm, "¥"+goodsMap.get("salesPrice").toString());

        HashMap<TextAttribute, Object> hm = new HashMap<TextAttribute, Object>();
        hm.put(TextAttribute.STRIKETHROUGH, TextAttribute.STRIKETHROUGH_ON);
//        hm.put(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_ON);
        hm.put(TextAttribute.SIZE, 30); // 定义字号
        hm.put(TextAttribute.FAMILY, "Arial"); // 定义字体名

        Font f2 = new Font(hm);
        g2d.setFont(f2);
        g2d.setColor(new Color(169,168,168));
        g2d.drawString("¥"+goodsMap.get("oldPrice").toString(), widthPrice+width+8,950);
        System.out.println(572);
        Font weiMaiMai = new Font("宋体", Font.ITALIC, 35);
        g2d.setFont(weiMaiMai);
        g2d.setColor(Color.black);
        g2d.drawString(wxName+"的名片", 50, 1100);

        Font des = new Font("宋体",Font.BOLD, 30);
        g2d.setFont(des);
        g2d.setColor(new Color(88,88,88));
        g2d.drawString("长按识别或扫描二维码,", 50, 1170);
        g2d.drawString("进入小程序后,您购买商", 50, 1210);
        g2d.drawString("品您的好友将会得到积分", 50, 1250);
        g2d.drawString("奖励。", 50, 1290);
        LOG.warn(map.get("shareUpId").toString()+":"+636);
        CommonResult result = this.getGoodsCode(map, token);
        if(result.isNotSuccess()){
            g2d.dispose();
            System.out.println(result.getMessage()+588);
            return result;
        }
        BufferedImage qrcode = ImageIO.read(new FileInputStream(result.getData().toString()));
        g2d.drawImage(qrcode.getScaledInstance(250, 250, Image.SCALE_SMOOTH), 450, 1060, null);

        //
        // 关闭资源
        g2d.dispose();
        File file=new File(result.getData().toString());
        if(file.exists()&&file.isFile()){
            System.out.println(result.getMessage()+599);
            file.delete();
        }
        ImageIO.write(appletImg, "png", new File(imgPath));
        String path = String.format("%s/%s", this.cfg.getNginxStaticImgUrl(), fileName);
        return CommonResult.returnDataWrapper(path);
    }

    public static void main(String[] str) throws IOException {
        File file = new File("F:\\mytemp\\x.png");
        BufferedImage appletImg = ImageIO.read(new FileInputStream("F:\\mytemp\\22.png"));
        Graphics2D g2d = appletImg.createGraphics();
        // 设置抗锯齿的属性
        g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
        System.out.println(appletImg.getWidth());
        System.out.println(appletImg.getHeight());
        //设置标题
        Font font = new Font("宋体", Font.ITALIC, 50);
        g2d.setFont(font);
        g2d.setColor(Color.black);
        g2d.drawString("商品名称", 50, 100);
        //填写商品图片

        BufferedImage bufferedImage = ImageIO.read(new FileInputStream("F:\\mytemp\\12.png"));
        if (bufferedImage.getWidth() > bufferedImage.getHeight()) {
            bufferedImage = bufferedImage.getSubimage(0, 0, bufferedImage.getHeight(), bufferedImage.getHeight());
        } else {
            bufferedImage = bufferedImage.getSubimage(0, 0, bufferedImage.getWidth(), bufferedImage.getWidth());
        }
        g2d.drawImage(bufferedImage.getScaledInstance(655, 655, Image.SCALE_SMOOTH), 47, 150, null);
        //写商品介绍
        String text="喜欢像是一阵风，而爱你是细水长流.流啊";
        if(text.length()>16){
            Font f = new Font("宋体", Font.BOLD, 25);
            g2d.setFont(f);
            g2d.setColor(Color.black);
            FontMetrics fm =sun.font.FontDesignMetrics.getMetrics(f);
            //16个字体一行
            int width = SwingUtilities.computeStringWidth(fm, text);
            int height = fm.getHeight();
            if(text.length()>=16 && text.length()<=23){
                g2d.drawString(text.substring(0,text.length()), 79,870);
                if(text.length()<=43 && text.length()>23){
                    g2d.drawString(text.substring(23,text.length())+"...", 79,870+height);
                }
            }
        }else {
            Font f = new Font("宋体", Font.BOLD, 35);
            g2d.setFont(f);
            g2d.setColor(Color.black);
            FontMetrics fm =sun.font.FontDesignMetrics.getMetrics(f);
            int width = SwingUtilities.computeStringWidth(fm, text);
            System.out.println(width);
            System.out.println(text.length());
            System.out.println((appletImg.getWidth()-width)/2);
            g2d.drawString(text.substring(0,text.length()), 79,880);
        }
        //写价格
        Font f1 = new Font("宋体", Font.BOLD, 38);
        g2d.setFont(f1);
        g2d.setColor(Color.red);
        g2d.drawString("¥180.00", 230,950);

        FontMetrics fm =sun.font.FontDesignMetrics.getMetrics(f1);
        int width = SwingUtilities.computeStringWidth(fm, "￥180.00");

        HashMap<TextAttribute, Object> hm = new HashMap<TextAttribute, Object>();
        hm.put(TextAttribute.STRIKETHROUGH, TextAttribute.STRIKETHROUGH_ON);
//        hm.put(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_ON);
        hm.put(TextAttribute.SIZE, 30); // 定义字号
        hm.put(TextAttribute.FAMILY, "Arial"); // 定义字体名

        Font f2 = new Font(hm);
        g2d.setFont(f2);
        g2d.setColor(new Color(169,168,168));
        g2d.drawString("¥150.00", 230+width,950);

        Font weiMaiMai = new Font("宋体", Font.ITALIC, 35);
        g2d.setFont(weiMaiMai);
        g2d.setColor(Color.black);
        g2d.drawString("祈祷的名片", 50, 1100);

        Font des = new Font("宋体",Font.BOLD, 30);
        g2d.setFont(des);
        g2d.setColor(new Color(88,88,88));
        g2d.drawString("长按识别或扫描二维码,", 50, 1170);
        g2d.drawString("进入小程序后,您购买商", 50, 1210);
        g2d.drawString("品您的好友将会得到积分", 50, 1250);
        g2d.drawString("奖励。", 50, 1290);

        BufferedImage qrcode = ImageIO.read(new FileInputStream("F:\\mytemp\\oPQnc4hfKj3Mynqmt9ad1yI3HaDI.png"));
        g2d.drawImage(qrcode.getScaledInstance(250, 250, Image.SCALE_SMOOTH), 450, 1060, null);

        //
        // 关闭资源
        g2d.dispose();
        ImageIO.write(appletImg, "png", new File("F:\\mytemp\\y.png"));
    }
}
